//
//  EditTankTableView.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/7/26.
//

import UIKit
import RxSwift
import RxGesture
import RxCocoa

class EditTankTableView:  TableView {
    lazy var diposeBag = DisposeBag()
    @objc dynamic var list = [InstallationDetailSystemDetailForHeaterModel]()
    var delList = [InstallationDetailSystemDetailForHeaterModel]()
    override func setUpView() {
        self.dataSource = self
        self.isScrollEnabled = true
        self.estimatedRowHeight = 300
        self.rowHeight = UITableView.automaticDimension
        self.backgroundColor = UIColor(hexStr: Constant.TransparentColorHexStr)
        self.register(EditTankTableViewCell.self, forCellReuseIdentifier: EditTankTableViewCell.reuseCellIdentifier)
        if #available(iOS 15.0, *) {//iOS 15会默认有22点的高度,需要代码设置为0
            self.sectionHeaderTopPadding = 0
        }
    }
    func addOneTank(){
        let newRow = InstallationDetailSystemDetailForHeaterModel()
        self.list.append(newRow)//insert(newRow, at: 0)
        self.reloadData()
    }
    func loadData(_ panels: [InstallationDetailSystemDetailForHeaterModel]){
        self.list = panels
        self.reloadData()
    }
}
extension EditTankTableView: UITableViewDataSource, UITextFieldDelegate{
    //UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell  = EditTankTableViewCell(style: .default, reuseIdentifier: EditTankTableViewCell.reuseCellIdentifier)
        
        cell.selectModelClosure = {[weak self]  in
            guard let strongSelf = self else { return}
            strongSelf.showSelectModelView(indexPath.row){
                //通知数据校验:单元格中的编辑事件，dynamic list监听不到，list只能监听到新增删除
                strongSelf.rx.list.onNext(strongSelf.list)
            }
        }
        //监听编辑事件，及时更新output数据的显示
        cell.countTextfield.editingChangedClosure = {[weak self](qty) in
            guard let strongSelf = self else { return}
            if let data = Int64(qty) {
                strongSelf.list[indexPath.row].number_heaters = data
            }else{
                strongSelf.list[indexPath.row].number_heaters = 0
            }
            //通知数据校验:单元格中的编辑事件，dynamic list监听不到，list只能监听到新增删除
            strongSelf.rx.list.onNext(strongSelf.list)
        }
        cell.deleteRowClosure = {[weak self]  in
            guard let strongSelf = self else { return}
            let panelModel  = strongSelf.list[indexPath.row]
            if panelModel.model != ""{
                Tool().showAlertViewWithTwoBtns(title: R.string.localizable.pleaseConfirm(),message: R.string.localizable.areYouSureToDelete(panelModel.model), cancelStr: R.string.localizable.cancel(), confirmStr: R.string.localizable.delete(),yesClosure: {
                    strongSelf.deletePanel(indexPath.row)
                })
            }else{
                strongSelf.deletePanel(indexPath.row)
            }
        }
        //是否是二手的
        cell.isSecondHandwitchClosure = {[weak self] (isOn) in
            guard let strongSelf = self else { return}
            strongSelf.list[indexPath.row].second_hand_flg = isOn
        }
        //是不是在原来有热水器的基础上，又增加了一个热水器
        cell.isMoreThanOneSwitchClosure = {[weak self] (isOn) in
            guard let strongSelf = self else { return}
            strongSelf.list[indexPath.row].multi_heater_flg = isOn
        }
        cell.setData(list, row: indexPath.row)
        return cell
    }
    private func deletePanel(_ row: Int){
        let panelModel  = self.list[row]
        if panelModel.id != 0 {//来自服务器的数据，加入删除list
            panelModel.deleted_at = true
            self.delList.append(panelModel)
        }
        self.list.remove(at: row)
        self.reloadData()
    }
    func showSelectModelView(_ row: Int,closure: @escaping (()->Void)){
        var installDate = ""
        if  self.list[row].id > 0 {//编辑Job的
            installDate = DateUtil().convertDateStrToDateStr(dateStr: JobDetailModelHelper.shared.jobDetailModel.system_detail.installation_date, oldFormat: "dd/MM/yyyy", newFormat: "yyyy-MM-dd")
        }else{//创建Job的
            installDate = DateUtil().getDatetimeStr(CreateJobModelHelper.shared.createJobViewModel.installDate,format: "yyyy-MM-dd",timeZone: TimeZone.current)
        }
        Tool().showSearchModelView(type: .tank,title: "Tank Model",installDate: installDate) {[weak self] result in
            guard let strongSelf = self else { return}
            if row < strongSelf.list.count{
                strongSelf.list[row].heater_brand_id = result.id
                strongSelf.list[row].brand = result.name
                strongSelf.list[row].model = result.model_number
                strongSelf.list[row].approved_date = result.approved_date
                strongSelf.list[row].expiry_date = result.expiry_date
                strongSelf.list[row].number_heaters = 1//默认为1
                strongSelf.reloadRows(at: [IndexPath(row: row, section: 0)], with: UITableView.RowAnimation.none)
                closure()
            }
        }
    }
}
